package cn.sollyu.SDManager;

import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;

import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import cn.sollyu.SDManger.R;

public class FileManagerService
{
	private  String	pathString	= null;
	private Context	context		= null;
	public static final String TAG_FILEBUG = "FileDug";
	
	
	public String getPathString() {
		return pathString;
	}

	// 要想使用FileManagerService必须传递一个上下文和文件路径
	public FileManagerService(Context context,String pathString) {
		this.context = context;
		this.pathString = pathString;
	}

	public ArrayList<HashMap<String, Object>> getFileList() {
		//生成一个新的文件列表数组
		ArrayList<HashMap<String, Object>> arrayList = new ArrayList<HashMap<String,Object>>();	
		
		File sdPath = null;
		try
		{
			sdPath = new File(pathString);
		} catch (Exception e)
		{
			Toast.makeText(context, e.toString(), 1).show();
			return arrayList;
		}
		int sum = 0;						// 总文件记录
		
		// 如果不是文件夹，就返回一个空的数组
		if (sdPath.isDirectory() == false) {return arrayList;}
		
		String sDStateString = Environment.getExternalStorageState();	// 获得SDCard卡的状态
		
		// 如果内存卡可以读写
		if (sDStateString.equals(Environment.MEDIA_MOUNTED))
		{
			sum = sdPath.listFiles().length;
			if (sum > 0)
			{
				for (File file : sdPath.listFiles())
				{
					// 查找到本文件夹下文件名称（绝对路径）
					String subFileNameString = pathString  + "/" + file.getName();
					String subFileUrl = getFileUri(subFileNameString);
					
					// 如果这个文件是文件夹
					DatabaseManagerService databaseManagerService = new DatabaseManagerService(context);
					HashMap<String, Object> hashMap = new HashMap<String, Object>();
					hashMap.put(context.getString(R.string.hashMapPath), subFileNameString);
					hashMap.put(context.getString(R.string.hashMapName), file.getName());
					hashMap.put(context.getString(R.string.hashMapUri), subFileUrl);
					hashMap.put(context.getString(R.string.hashMapInfo), databaseManagerService.getInfoString(subFileNameString));
					hashMap.put(context.getString(R.string.hashMapSoftware), databaseManagerService.getSoftString(subFileNameString));
					hashMap.put(context.getString(R.string.hashMapIndex), databaseManagerService.getIndexString(subFileNameString));
					hashMap.put(context.getString(R.string.hashMapDel), databaseManagerService.getDelString(subFileNameString));
					hashMap.put(context.getString(R.string.hashMapIcon), getFileIcon(subFileUrl));
					hashMap.put(context.getString(R.string.hashMapIsDir), new File(subFileNameString).isDirectory() ? 0 : 1);
					arrayList.add(hashMap);
				}
			}
		}

		
		return arrayList;
	}
	
	public boolean checkExtWithArrayString(String pString,String[] arrayStrings) {
		for (String aString : arrayStrings)
		{
			if (pString.endsWith(aString)) return true;
		}
		return false;
	}
	
	private String getFileUri(String pString) {
		if (checkExtWithArrayString(pString.toLowerCase(),context.getResources().getStringArray(R.array.fileEndingAudio)))
		{
			return context.getString(R.string.file_type_audio);
		}
		else if (checkExtWithArrayString(pString.toLowerCase(),context.getResources().getStringArray(R.array.fileEndingImage)))
		{
			return context.getString(R.string.file_type_image);
		}
		else if (checkExtWithArrayString(pString.toLowerCase(),context.getResources().getStringArray(R.array.fileEndingText)))
		{
			return context.getString(R.string.file_type_text);
		}
		else if (pString.toLowerCase().endsWith(context.getString(R.string.fileEndingApk))) 
		{
			return context.getString(R.string.file_type_apk);
		}
		
		else if (new File(pString).isDirectory()) {
			return context.getString(R.string.file_type_folder);
		}else 
		{
			return "*/*";
		}
		
	}
	
	private int getFileIcon(String pFileUriString) {
		if (pFileUriString == null) return R.drawable.icon;
		
		if (pFileUriString.equals(context.getString(R.string.file_type_folder)))
		{
			return R.drawable.folder;
		}
		else if (pFileUriString.equals(context.getString(R.string.file_type_audio)))
		{
			return R.drawable.file_type_audio;
		}
		else if (pFileUriString.equalsIgnoreCase(context.getString(R.string.file_type_image)))
		{
			return R.drawable.file_type_img;
		}
		else if (pFileUriString.equalsIgnoreCase(context.getString(R.string.file_type_text)))
		{
			return R.drawable.file_type_text;
		}
		else if (pFileUriString.equals(context.getString(R.string.file_type_apk)))
		{
			return R.drawable.file_type_apk;
		}
		
		return R.drawable.file_type_unknow;
	}

	/**
	 * 说明：根据文件名进行排序
	 * */
	public void sortByFileName(ArrayList<HashMap<String, Object>> arrayList) {
		Collections.sort(arrayList, new Comparator<  HashMap<String, Object>>()   
		{   
			@Override
			public int compare(HashMap<String, Object> object1, HashMap<String, Object> object2) {
				return object1.get(context.getString(R.string.hashMapName)).toString().compareTo(object2.get(context.getString(R.string.hashMapName)).toString());
			}  
		}); 
		
	};
	
	/**
	 * 说明：根据文件类型进行排序
	 * */
	public void sortByFileType(ArrayList<HashMap<String, Object>> arrayList) {
		Collections.sort(arrayList, new Comparator<  HashMap<String, Object>>()   
		{   
			@Override
			public int compare(HashMap<String, Object> object1, HashMap<String, Object> object2) {
//				return object1.get(context.getString(R.string.hashMapIsDir)).toString().compareTo(object2.get(context.getString(R.string.hashMapIsDir)).toString());
				int a = object1.get(context.getString(R.string.hashMapIsDir)).toString().compareTo(object2.get(context.getString(R.string.hashMapIsDir)).toString());
//				int b = object1.get(context.getString(R.string.hashMapName)).toString().compareTo(object2.get(context.getString(R.string.hashMapName)).toString());
				return a ;
			}  
		}); 
		
	};
	
	/**
	 * 说明：根据文件类型进行排序
	 * */
	public void sortByFileDelNo(ArrayList<HashMap<String, Object>> arrayList) {
		Collections.sort(arrayList, new Comparator<  HashMap<String, Object>>()   
		{   
			@Override
			public int compare(HashMap<String, Object> object1, HashMap<String, Object> object2) {
				return object2.get(context.getString(R.string.hashMapInfo)).toString().compareTo(object1.get(context.getString(R.string.hashMapInfo)).toString());
			}  
		}); 
		
	};
	
	/**
	* 删除文件，可以是单个文件或文件夹
	* @param   pathString    待删除的文件名
	* @return 文件删除成功返回true,否则返回false
	*/
	public  boolean delete() {
		
		File file = new File(pathString);
		if (!file.exists())
		{
			Log.i(TAG_FILEBUG, "删除文件失败：" + pathString + "文件不存在");
			return false;
		} else
		{
			if (file.isFile())
			{
				return deleteFile(pathString);
			} else
			{
				return deleteDirectory(pathString);
			}
		}
	}
		
	/**
	 * 
	 * 删除单个文件
	 * 
	 * @param pathString
	 *                被删除文件的文件名
	 * 
	 * @return 单个文件删除成功返回true,否则返回false
	 */
	public static boolean deleteFile(String pathString) {
		File file = new File(pathString);
		if (file.isFile() && file.exists() && file.delete())
		{
			Log.i(TAG_FILEBUG, "删除单个文件" + pathString + "成功！");
			return true;
		} else
		{
			Log.i(TAG_FILEBUG, "删除单个文件" + pathString + "失败！");
			return false;
		}
	}

	/**
	 * 
	 * 删除目录（文件夹）以及目录下的文件
	 * 
	 * @param dir
	 *                被删除目录的文件路径
	 * 
	 * @return 目录删除成功返回true,否则返回false
	 */
	public static boolean deleteDirectory(String dir) {
		// 如果dir不以文件分隔符结尾，自动添加文件分隔符
		if (!dir.endsWith(File.separator))
		{
			dir = dir + File.separator;
		}
		File dirFile = new File(dir);
		// 如果dir对应的文件不存在，或者不是一个目录，则退出
		if (!dirFile.exists() || !dirFile.isDirectory())
		{
			Log.i(TAG_FILEBUG, "删除目录失败" + dir + "目录不存在！");
			return false;
		}
		boolean flag = true;
		// 删除文件夹下的所有文件(包括子目录)
		File[] files = dirFile.listFiles();
		for (int i = 0; i < files.length; i++)
		{
			// 删除子文件
			if (files[i].isFile())
			{
				flag = deleteFile(files[i].getAbsolutePath());
				if (!flag)
				{
					break;
				}
			}
			// 删除子目录
			else
			{
				flag = deleteDirectory(files[i]
						.getAbsolutePath());
				if (!flag)
				{
					break;
				}
			}
		}
		if (!flag)
		{
			Log.i(TAG_FILEBUG, "删除目录失败");
			return false;
		}
		// 删除当前目录
		if (dirFile.delete())
		{
			Log.i(TAG_FILEBUG, "删除目录" + dir + "成功！");
			return true;
			
		} else
		{
			Log.i(TAG_FILEBUG, "删除目录" + dir + "失败！");
			return false;
		}
		
	}

	public double getFileSizes(File file) throws Exception {// 取得文件大小
		double fileSize = 0;
		if (file.exists())
		{
			FileInputStream fis = null;
			fis = new FileInputStream(file);
			fileSize = fis.available();
		} else
		{
			file.createNewFile();
			System.out.println("文件不存在");
		}
		return fileSize;
	}

	public double getFileSize(File filef) throws Exception// 取得文件夹大小
	{
		double size = 0;
		File flist[] = filef.listFiles();
		for (int i = 0; i < flist.length; i++)
		{
			if (flist[i].isDirectory())
			{
				size = size + getFileSize(flist[i]);
			} else
			{
				size = size + flist[i].length();
			}
		}
		return size;
	}
	
	public String FormetFileSize(double fileS) {// 转换文件大小
		DecimalFormat df = new DecimalFormat("#.00");
		String fileSizeString = "";
		if (fileS < 1024)
		{
			fileSizeString = df.format((double) fileS) + "B";
		} else if (fileS < 1048576)
		{
			fileSizeString = df.format((double) fileS / 1024) + "K";
		} else if (fileS < 1073741824)
		{
			fileSizeString = df.format((double) fileS / 1048576) + "M";
		} else
		{
			fileSizeString = df.format((double) fileS / 1073741824) + "G";
		}
		return fileSizeString;
	}
	
	public long getlist(File file) {// 递归求取目录文件个数
		long size = 0;
		File flist[] = file.listFiles();
		size = flist.length;
		for (int i = 0; i < flist.length; i++)
		{
			if (flist[i].isDirectory())
			{
				size = size + getlist(flist[i]);
				size--;
			}
		}
		return size;
	}
		
}
